package org.baixin.interceptor;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.baixin.entity.User;
import org.springframework.stereotype.Component;

/**
 * 
 * 
 * @author slaton.wu@gmail.com
 * @version 1.0
 * @created 2011-6-12 下午06:43:49
 */
@Component("PermissionInterceptor")
public class PermissionInterceptor implements Filter {

	private HttpSession session;
	/**
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		
		if (session!=null) {
			session.removeAttribute("login_user");
		}
	}

	/**
	 * @param req
	 * @param resp
	 * @param chain
	 * @throws IOException
	 * @throws ServletException
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		 HttpServletRequest request = (HttpServletRequest)req;
		this.session = request.getSession();
		if(verify(request)){
			((HttpServletResponse)resp).sendRedirect(request.getContextPath()+"/user/login.htm");
			return ;
		}
		chain.doFilter(req, resp);
	}

	/**
	 * @param arg0
	 * @throws ServletException
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig config) throws ServletException {
		System.out.println("111");
	}
	
	public Boolean verify(HttpServletRequest request){
		User user = (User) session.getAttribute("login_user");
		String uri = request.getRequestURI();
		if (StringUtils.contains(uri, "login.htm")||StringUtils.contains(uri, "loginUser.htm")||user!=null) {
			return false;
		}
		return true;
	}

}
